package cn.ljy.authority.web.controller.backstage.authority;


import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.model.SysUser;
import cn.ljy.authority.model.query.SysUserQuery;
import cn.ljy.authority.service.SysPermissionService;
import cn.ljy.authority.service.SysUserExcelService;
import cn.ljy.authority.service.SysUserService;
import cn.ljy.authority.web.controller.backstage.BaseBackstageController;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.common.model.result.ExcelImportResult;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.utils.file.MyFileUpload;
import cn.ljy.common.utils.table.MyTableUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Api(tags = "后台账户管理模块")
@RestController
@RequestMapping(value = "/api/backstage/authority/usermanage")
public class SysUserManageController extends BaseBackstageController<SysUser, SysUserQuery,Long> {

    @Autowired
    private SysUserService baseService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private SysUserExcelService sysUserExcelService;

    @ApiOperation(value = "分页查询账户列表")
    @PreAuthorize("hasAuthority('sys:user:manage:query')")
    public ResponseData query(Integer page, Integer pageSize,SysUserQuery sysUserQuery){
       return super.query(page, pageSize, sysUserQuery);
    }

    @ApiOperation(value = "批量删除账户")
    @PreAuthorize("hasAuthority('sys:user:manage:del')")
    @Override
    public ResponseData deletes(@NotEmpty(message = "操作失败：请选择要移除的记录") Long[] ids) {
       return super.deletes(ids);
    }

    @ApiOperation(value = "添加账户")
    @PreAuthorize("hasAuthority('sys:user:manage:add')")
    @Override
    public ResponseData add(@Valid @RequestBody SysUser sysUser) {
       return super.add(sysUser);
    }

    @ApiOperation(value = "编辑账户")
    @PreAuthorize("hasAuthority('sys:user:manage:edit')")
    @Override
    public ResponseData edit(@Valid @RequestBody SysUser sysUser) {
        return super.edit(sysUser);
    }

    @ApiOperation(value = "读取指定账户信息")
    @PreAuthorize("hasAuthority('sys:user:manage:query')")
    @Override
    public ResponseData get(@PathVariable Long id) {
        return super.get(id);
    }

    //======================================扩展操作=====================================================//


    @ApiOperation(value = "获取指定账户的树形菜单")
    @PreAuthorize("hasAuthority('sys:user:manage:permission:query')")
    @GetMapping("/{id}/permission/tree")
    public ResponseData getTreeMenus(@PathVariable Long id,@NotNull(message="缺少isMenu参数") Boolean isMenu){
        //获取当前登陆账户的权限集合
        return  ResponseData.success(sysPermissionService.getTreePermission(id,isMenu));
    }


    @ApiOperation(value = "上传用户头像")
    @PreAuthorize("hasAuthority('sys:user:manage:edit')")
    @PostMapping("/{id}/uploadPhoto")
    public ResponseData uploadImage(@PathVariable @NotNull(message="请传入账户id") Long id,@NotNull(message="请选择上传文件") MultipartFile file){
        // 获取相关用户
        SysUser user=baseService.get(id);
        if(user!=null){
            // 为该用户上传头像，并获取上传成功后的头像图片网址
            String fileName=baseService.uploadHeadImgFile(user,file);
            return ResponseData.success(fileName);
        }else{
            return ResponseData.error("用户不存在");
        }
    }


    /**
     * 上传表格，并导入到项目中
     * @param file 要上传的excel
     * @return
     */
    @ApiOperation(value = "导入账户表excel数据")
    @PreAuthorize("hasAuthority('sys:user:manage:excel:upload')")
    @PostMapping("/excel")
    public ResponseData uploadExcel(MultipartFile file) throws Exception{
        if(file!=null&&!file.isEmpty()){
            String fileName=file.getOriginalFilename();//获取文件名
            String extensionName=FileUtil.extName(fileName);//获取文件扩展名
            //验证表格的格式是否正确
            MyFileUpload.validateExtByDir(extensionName,"table");
            //执行表格导入
            ExcelImportResult result=sysUserExcelService.addUsersFromExcel(file.getInputStream(), UserUtil.getLoginUser());
            //String filePath=uploadFolder+Constant.MATERIAL_EXCEL_UPLOAD_PATH;//获取excel上传后保存的物理路径
            return ResponseData.success(result);
        }else{
            throw new MyWebException("操作失败：请选择上传文件");
        }
    }

    /**
     * 导出表格模板
     */
    @ApiOperation(value = "导出账户模块的excel数据")
    @GetMapping("/excel")
    public void downloadExcel(HttpServletResponse response,SysUserQuery sysUserQuery){
        ExcelWriter writer=sysUserExcelService.exportExcel(false,sysUserQuery);
        MyTableUtil.downloadExcelByHutool(response,"账户表格",writer);
    }

    /**
     * 导出表格
     */
    @ApiOperation(value = "导出账户的excel模板")
    @GetMapping("/excel/template")
    public void downloadExcelTemplate(HttpServletResponse response){
        ExcelWriter writer=sysUserExcelService.exportExcel(true,null);
        MyTableUtil.downloadExcelByHutool(response,"账户表格模板",writer);
    }


}
